package top.zerozoo.learn.grade.servlet;

import org.apache.commons.beanutils.BeanUtils;
import top.zerozoo.learn.grade.factory.ServiceFactory;
import top.zerozoo.learn.grade.service.CourseScoreService;
import top.zerozoo.learn.grade.util.NumberUtils;
import top.zerozoo.learn.grade.vo.QueryScoreCondition;
import top.zerozoo.learn.grade.vo.QueryScoreInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/queryScore.do")
public class QueryScoreServlet extends HttpServlet {
    private final CourseScoreService courseScoreService = ServiceFactory.get(CourseScoreService.class);

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int currentPage = NumberUtils.parse(req.getParameter("currentPage"), Integer.class, 1);
        int rows = NumberUtils.parse(req.getParameter("rows"), Integer.class, 20);

        QueryScoreCondition condition = new QueryScoreCondition();
        try {
            BeanUtils.populate(condition, req.getParameterMap());
        } catch (Exception e) {
            e.printStackTrace();
        }

        QueryScoreInfo queryScoreInfo = new QueryScoreInfo();
        queryScoreInfo.setPageInfo(courseScoreService.find(currentPage, rows, condition));
        queryScoreInfo.setCondition(condition);

        req.setAttribute("info", queryScoreInfo);
        req.getRequestDispatcher("/queryScore.jsp").forward(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
